package com.atguigu.gmall.item.service.impl;

import com.atguigu.gmall.feign.product.CategoryFeignClient;
import com.atguigu.gmall.feign.product.SaleAttrFeignClient;
import com.atguigu.gmall.feign.product.SkuInfoFeignClient;
import com.atguigu.gmall.item.service.ItemService;
import com.atguigu.gmall.model.product.BaseCategoryView;
import com.atguigu.gmall.model.product.SkuImage;
import com.atguigu.gmall.model.product.SkuInfo;
import com.atguigu.gmall.model.product.SpuSaleAttr;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    SkuInfoFeignClient skuInfoFeignClient;

    @Autowired
    CategoryFeignClient categoryFeignClient;

    @Autowired
    SaleAttrFeignClient saleAttrFeignClient;

    ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 查询商品详情 - 1、查询sku的详情数据
     * @param skuId
     * @return
     */
    @Override
    public Map<String, Object> getItemDetail(Long skuId) throws JsonProcessingException {
        Map<String, Object> data = new HashMap<>();
        //准备好以下数据

        //1、categoryView（category1Id、category1Name、category2Id、category2Name、category3Id、category3Name）
        // 代表当前sku 所在的完整三级分类信息--查询sku对应的分类所在完整路径
        BaseCategoryView categoryView = categoryFeignClient.getCategoryPathBySkuId(skuId);
        data.put("categoryView",categoryView);

        //2、skuInfo（skuName、id、skuDefaultImg、skuImageList.....）  代表当前sku的详情，来源于数据库sku_info表
        SkuInfo skuInfo = skuInfoFeignClient.getSkuInfo(skuId);
        data.put("skuInfo",skuInfo);

        //2.1、查询当前sku对应的所有图片
        List<SkuImage> skuInfoimages = skuInfoFeignClient.getSkuInfoimages(skuId);
        skuInfo.setSkuImageList(skuInfoimages);

        //3、price-价格 单独查一下
        BigDecimal price = skuInfoFeignClient.getSkuPrice(skuId);
        data.put("price",price);

        //4、spuSaleAttrList 当前sku对应的spu的所有销售属性值组合; 标当前sku对应的那种组合
        Long spuId = skuInfo.getSpuId();
        List<SpuSaleAttr> spuSaleAttrList = saleAttrFeignClient.getSpuSaleAttrBySpuId(skuId,spuId);
        data.put("spuSaleAttrList",spuSaleAttrList);


        //5、valuesSkuJson   包含了每一种销售属性组合对应是哪个skuId。方便浏览器跳转
        //map key:176|178 value :52 == 一组key等于一个value
        Map<String,Object> valuesSkuJson = saleAttrFeignClient.getSpuDeSkuSaleAttrValuesZuhe(spuId);
        //前端需要的是字符串
        String jsonstring = objectMapper.writeValueAsString(valuesSkuJson);
        data.put("valuesSkuJson",jsonstring);
        return data;
    }
}
